from machine import Pin

import time

# esp8266         HC-SR04
# vin                vcc
# GND                GND
# IO13(D7)           Echo
# IO15(D8)           Trig

Trig = Pin(15, Pin.OUT)
Echo = Pin(13, Pin.IN)

while True:

    Trig.value(1)

    time.sleep_us(20)

    Trig.value(0)

    while (Echo.value() == 0):
        Trig.value(1)

        time.sleep_us(20)

        Trig.value(0)

    if (Echo.value() == 1):

        ts = time.ticks_us()

        while (Echo.value() == 1):
            pass

        te = time.ticks_us()

        tc = te - ts

        distance = (tc * 0.034) / 2

        print('Distance:', distance, 'cm')

        try:
            import oled
            oled.show(str(distance) + 'cm')
        except Exception:
            print('oled error:'+Exception)
            pass

    time.sleep(2)
